package com.mantru.iotpot.Cook.fragment;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Cook.adapter.FirePowerAdapter;
import com.mantru.iotpot.DateClass.FirePowerDate;
import com.mantru.iotpot.R;
import com.mantru.iotpot.eventbus.FoodEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FirePowerFragmrnt#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class FirePowerFragmrnt extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private Context context;
    private View rootview;
    private ApplicationClass ac;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private int sid;
    private int vegetableId;
    private List<FirePowerDate> firePowerDataList;
    private RecyclerView recyclerView;

    // 定义接口用于数据传递
    public interface OnDataPassListener {
        void onDataPass(List<FirePowerDate> firePowerDataList);
    }
    private OnDataPassListener onDataPassListener;
    // 提供一个方法来获取当前的数据
    // 提供一个方法来获取当前的数据
    public List<FirePowerDate> getCurrentData() {
        // 从适配器中获取最新的数据
        FirePowerAdapter adapter = (FirePowerAdapter) recyclerView.getAdapter();
        if (adapter != null) {
            return adapter.getFirePowerDataList(); // 调用适配器的方法获取数据
        }
        return new ArrayList<>(); // 如果适配器为空，返回空列表
    }

    public static FirePowerFragmrnt newInstance(String param1, String param2) {
        FirePowerFragmrnt fragment = new FirePowerFragmrnt();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public FirePowerFragmrnt() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        EventBus.getDefault().register(this);
    }

    public FirePowerFragmrnt(Context context) {
        this.context = context;
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        try {
            onDataPassListener = (OnDataPassListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement OnDataPassListener");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.fragment_fire_power_fragmrnt, container, false);
        ac = (ApplicationClass) getActivity().getApplication();// 初始化 ApplicationClass
        recyclerView = rootview.findViewById(R.id.frie_power_fragment_recyclerview);
        // 初始化 firePowerDataList
        firePowerDataList = new ArrayList<>();
        getJson();//获取json数据
        // 设置 RecyclerView 的适配器
        FirePowerAdapter adapter = new FirePowerAdapter(firePowerDataList,context);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        if (firePowerDataList == null || firePowerDataList.size() == 0){
            recyclerView.setAdapter(null);
        }else {
            recyclerView.setAdapter(adapter);
        }
        // 添加滚动监听器
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 滚动状态改变时的逻辑
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    updateAllBubbles(recyclerView);
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 滚动时的逻辑（可选）
            }
        });
        return rootview;
    }

    // 一个用于获取和解析 JSON 数据的方法
    private void getJson() {
        Log.d("FirePowerFragment","vegetableId1: " + vegetableId + " sid1: " + sid);
        String json_data = ac.GetSQLData_Cooking_Config_Fire(vegetableId, sid);
        try {
            JSONObject jsonObject = new JSONObject(json_data);
            Log.d("FirePowerFragment","jsonObject: " + jsonObject);
            boolean success = jsonObject.getBoolean("success");
            Log.d("FirePowerFragment","success: " + success);
            if (success) {
                JSONArray dataArray = jsonObject.getJSONArray("data");
                Log.d("FirePowerFragment","dataArray.length()" + dataArray.length());
//                firePowerDataList.clear(); // 清空列表
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject item = dataArray.getJSONObject(i);
                    String steep_index = item.getString("steep_index");
                    String title1 = item.getString("title1");
                    String title2 = item.getString("title2");
                    String value = item.getString("value");
                    String min_value = item.getString("min_value");
                    String max_value = item.getString("max_value");
                    String unit = item.getString("unit");
                    String step_value = item.getString("step_value");
                    int is_show = item.getInt("is_show");
                    FirePowerDate firePowerDate = new FirePowerDate(
                            steep_index,
                            title1,
                            title2,
                            value,
                            min_value,
                            max_value,
                            unit,
                            step_value,
                            is_show
                    );
                    firePowerDataList.add(firePowerDate);
                    Log.d("FirePowerFragment", "steep_index: " + steep_index + " title1: " + title1 + " title2: " + title2
                    + " value: " + value + " min_value: " + min_value + " max_value: " + max_value + " unit: " + unit + " step_value: " +step_value
                    + " is_show: " + is_show);
                }
            } else {
                Log.e("FirePowerFragment", "Failed to get JSON data");
                Toast.makeText(context, "解析json数据失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e("FirePowerFragment", "Error parsing JSON: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onEvent(FoodEvent event) {
        // 接收事件并处理数据
        sid = event.getSid();
        vegetableId = event.getVegetableId();
        Log.d("FirePowerFragment", "Received sid: " + sid + ", vegetableId: " + vegetableId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //让显示的项更新气泡的位置以及seekbar滑块的位置
    private void updateAllBubbles(RecyclerView recyclerView) {
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View childView = recyclerView.getChildAt(i);
            RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(childView);
            if (viewHolder instanceof FirePowerAdapter.FirePowerViewHolder) {
                int position = viewHolder.getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    FirePowerAdapter.FirePowerViewHolder holder = (FirePowerAdapter.FirePowerViewHolder) viewHolder;
                    // 更新气泡位置
                    ((FirePowerAdapter) recyclerView.getAdapter()).updateSeekBarAndBubble(holder, position);
                }
            }
        }
    }
}